package org.wanho.shop.servlet;

import org.wanho.shop.service.CartService;
import org.wanho.shop.service.impl.CartServiceImpl;
import org.wanho.shop.vo.Cart;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author：汤小洋
 * Date：2023-04-26 15:10
 * Description：<描述>
 */
@WebServlet("*.cart")
public class CartServlet extends HttpServlet {

    private CartService cartService = new CartServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        if("/add.cart".equals(path)){
            add(req,resp);
        }else if("/removeById.cart".equals(path)){
            removeById(req,resp);
        }else if("/modify.cart".equals(path)){
            modify(req,resp);
        }else if("/clear.cart".equals(path)){
            clear(req,resp);
        }else if("/removeByIds.cart".equals(path)){
            removeByIds(req,resp);
        }
    }

    private void removeByIds(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        String[] ids = req.getParameterValues("productId");

        for(String id : ids){
            cartService.removeById(cart,Integer.parseInt(id));
        }
        resp.sendRedirect(req.getContextPath()+"/jsp/cart.jsp");
    }

    private void clear(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.getSession().setAttribute("cart", new Cart());
        resp.sendRedirect(req.getContextPath()+"/jsp/cart.jsp");
    }

    private void modify(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int productId = Integer.parseInt(req.getParameter("id"));
        int num = Integer.parseInt(req.getParameter("num"));
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        cartService.modify(cart,productId,num);
        resp.sendRedirect(req.getContextPath()+"/jsp/cart.jsp");
    }

    private void removeById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int productId = Integer.parseInt(req.getParameter("id"));
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        cartService.removeById(cart, productId);
        resp.sendRedirect(req.getContextPath()+"/jsp/cart.jsp");
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        int productId = Integer.parseInt(req.getParameter("id"));
        Cart cart = (Cart) req.getSession().getAttribute("cart");

        cartService.add(cart, productId);
        req.setAttribute("msg","添加购物车成功！");
        req.getRequestDispatcher("/findAll.product").forward(req,resp);
    }
}
